package com.tgpms.web.element.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.util.Common;
import com.tgpms.util.PageInfo;
import com.tgpms.util.VformBeanUtil;
import com.tgpms.web.element.dao.WsElementMapper;
import com.tgpms.web.element.dto.D1120Dto;
import com.tgpms.web.element.dto.D1130Dto;
import com.tgpms.web.element.entity.CommodityMaster;
import com.tgpms.web.element.entity.TaggedEquipment;
import com.tgpms.web.element.entity.WsElement;
import com.tgpms.web.element.service.ITaggedEquipmentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jl
 * Created on 2020/7/10
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class TaggedEquipmentServiceImpl implements ITaggedEquipmentService {
    @Autowired
    private VformInterface vformInterface;
    @Autowired
    private WsElementMapper wsElementMapper;

    @Override
    public Result selTaggedEquipmentList(PageInfo pageInfo) {
        JSONObject param = new JSONObject();
        Object selparam = pageInfo.getQueryMap().get("selparam");
        Object leftdition = pageInfo.getQueryMap().get("leftdition");
        Object condition = pageInfo.getQueryMap().get("condition");
        Object dataowner = pageInfo.getQueryMap().get("dataowner");
        if (Common.isEmpty(selparam)) {
            param.put("[SQL1]", " ");
        } else {
            param.put("[SQL1]", selparam.toString());
        }
        if (Common.isEmpty(leftdition)) {
            param.put("[SQL2]", " ");
        } else {
            param.put("[SQL2]", leftdition.toString());
        }
        if (Common.isEmpty(condition)) {
            param.put("[SQL3]", " ");
        } else {
            param.put("[SQL3]", condition.toString());
        }
        Result result = vformInterface.multiForMsQueryBySql("SCWZC042", param.toJSONString(), pageInfo.getPage(),
                pageInfo.getSize(), "Y", "Y", dataowner.toString());
        return result;
    }

    @Override
    public Map<String, String> addTaggedEquipmentInfo(TaggedEquipment en) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isBlank(en.getEqTagNo())){
            // 设置主键
            Result findResult = vformInterface.find("D1130","{\"COMMODITY_NUMBER=\":\""+en.getCommodityNumber()+"\"}","1","500","N","N","");
//            System.out.println("vform查询返回结果为:  "+findResult);
            if(findResult==null || !findResult.getSuccess()) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
                return map;
            }
            if(findResult.getData().toString().equals("{\"message\":\"login\"}")) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
                return map;
            }
            String eqTagNo;
            if(findResult.getData().toString().equals("[]")) {
                eqTagNo = "0000";
            }else {
                List<Map<String,String>> list = JSONArray.parseObject(findResult.getData().toString(), List.class);
                List<Integer> eqTagNos = new ArrayList<>();
                for(Map<String,String> m : list) {
                    eqTagNos.add(Integer.valueOf(m.get("EQ_TAG_NO").substring(en.getCommodityNumber().length())));
                }
                Integer max = eqTagNos.stream().max(Integer::compare).get();
                String s = String.format("%04d", max+1);
                eqTagNo = en.getCommodityNumber()+s;
            }
            en.setEqTagNo(eqTagNo);
        }
        // 正式环境数据
//        en.setEqCat("HBSW");
//        en.setEqStatus("A");
//        en.setEqSystem("HBSW");

        // 测试环境数据
        en.setEqType("E20");
        en.setEqCat("BG2");
        en.setEqStatus("A");
        en.setEqSystem("BE3");

        // 查询物资表
        Result findResult = vformInterface.find("D1120","{\"COMMODITY_NUMBER=\":\""+en.getCommodityNumber()+"\"}","1","1","N","N","");
        List<Map<String,String>> list = JSONArray.parseObject(findResult.getData().toString(), List.class);
        if (CollUtil.isNotEmpty(list)) {
            Map<String, String> stringStringMap = list.get(0);
            String unitOfMeasure = stringStringMap.get("UNIT_OF_MEASURE");
            // 设置单位
            en.setUnitOfMeasure(unitOfMeasure);
            // 设置EQ_FLAG
            en.setEqFlag(stringStringMap.get("COMMODITY_TYPE_CODE"));
        }

        //对象转json字符串, 字段驼峰转下划线大写字段
        JSONObject json = VformBeanUtil.entityToJsonString(en);
        if (json.isEmpty()) {
            map.put("code", "-2");
            map.put("info", ExceptionExplain.ERROR_BY_PARSING.getExplain());
            return map;
        }
//		System.out.println("vform增加上送参数   "+json.toString());
        //vform同步插入
        Result result = vformInterface.insert("D1130", json);
//		System.out.println("vform增加返回结果   "+result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        if (resData.equals("{\"message\":\"login\"}")) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
            return map;
        }
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
        }
        return map;
    }

    @Override
    public Map<String, String> updateTaggedEquipmentInfo(TaggedEquipment en) {
        Map<String, String> map = new HashMap<String, String>();
        JSONObject keyjson = new JSONObject();
        keyjson.put("EQ_TAG_NO", en.getEqTagNo());
        JSONObject pajson = VformBeanUtil.entityToJsonStringByUpdate(en);
        pajson.remove("EQ_TAG_NO");

//        System.out.println("vform更新上送主键   "+keyjson.toString());
//        System.out.println("vform更新上送参数   "+pajson.toString());
        //vform同步更新
        Result result = vformInterface.update("D1130", keyjson.toString(), pajson.toString(), null, null, null);
//        System.out.println("vform更新返回结果   "+result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
        }
        return map;
    }

    @Override
    public Map<String, String> deleteTaggedEquipmentInfo(String eqTagNo) {
        Result findResult = vformInterface.find("D1130","{\"EQ_TAG_NO=\":\""+eqTagNo+"\"}","1","1","N","N","");
        Map<String, String> map = new HashMap<String, String>();
        JSONObject keyjson = new JSONObject();
        keyjson.put("EQ_TAG_NO", eqTagNo);
//        System.out.println("vform删除上送主键   " + keyjson.toString());
        //vform同步删除
        Result result = vformInterface.delete("D11230", keyjson.toJSONString());
//        System.out.println("vform删除返回结果   " + result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            // 删除设备属性
//            List<Map<String,String>> list = JSONArray.parseObject(findResult.getData().toString(), List.class);
//            if (CollUtil.isNotEmpty(list)) {
//                Map<String, String> stringStringMap = list.get(0);
//                String commodityNumber = stringStringMap.get("COMMODITY_NUMBER");
//                wsElementMapper.delete(new LambdaQueryWrapper<WsElement>().eq(WsElement::commodityNumber,commodityNumber));
//            }
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
        }
        return map;
    }

    @Override
    public Map<String, String> batchImport(MultipartFile file,String project, String dataOwner, String insertName) {
        Map<String, String> map = new HashMap<>();

        ExcelReader reader;
        try {
            InputStream inputStream = file.getInputStream();
            reader = ExcelUtil.getReader(inputStream);

            List<D1130Dto> all = reader.readAll(D1130Dto.class);
            List<TaggedEquipment> collect = all.stream().map(e -> {
                TaggedEquipment taggedEquipment = new TaggedEquipment();
                taggedEquipment.setCommodityNumber(e.getCOMMODITY_NUMBER());
                taggedEquipment.setEqTagNo(e.getEQ_TAG_NO());
                taggedEquipment.setDescription(e.getDESCRIPTION());
                taggedEquipment.setBrand(e.getBRAND());
                taggedEquipment.setModelNo(e.getMODEL_NO());
                taggedEquipment.setRemarks(e.getREMARKS());
                taggedEquipment.setDataOwner(dataOwner);
                taggedEquipment.setProject(project);

                // 查询物资表
                Result findResult = vformInterface.find("D1120","{\"COMMODITY_NUMBER=\":\""+taggedEquipment.getCommodityNumber()+"\"}","1","1","N","N","");
                List<Map<String,String>> list = JSONArray.parseObject(findResult.getData().toString(), List.class);
                if (CollUtil.isNotEmpty(list)) {
                    Map<String, String> stringStringMap = list.get(0);
                    String unitOfMeasure = stringStringMap.get("UNIT_OF_MEASURE");
                    // 设置单位
                    taggedEquipment.setUnitOfMeasure(unitOfMeasure);
                    // 设置EQ_FLAG
                    taggedEquipment.setEqFlag(stringStringMap.get("COMMODITY_TYPE_CODE"));
                }

                // 正式环境数据
        //        taggedEquipment.setEqCat("HBSW");
        //        taggedEquipment.setEqStatus("A");
        //        taggedEquipment.setEqSystem("HBSW");

                // 测试环境数据
                taggedEquipment.setEqType("E20");
                taggedEquipment.setEqCat("BG2");
                taggedEquipment.setEqStatus("A");
                taggedEquipment.setEqSystem("BE3");
                taggedEquipment.setInsertUser(insertName);
                taggedEquipment.setInsertDate(DateUtil.now());
                return taggedEquipment;
            }).collect(Collectors.toList());

            JSONArray jsonArray = new JSONArray();
            collect.forEach(e -> {
                //对象转json字符串, 字段驼峰转下划线大写字段
                JSONObject json = VformBeanUtil.entityToJsonString(e);
                jsonArray.add(json);
            });
            //vform同步插入
            Result result = vformInterface.insertBatch("D1130", jsonArray);
            if (result == null || !result.getSuccess()) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
                return map;
            }
            String resData = result.getData().toString();
            if (resData.equals("{\"message\":\"login\"}")) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
                return map;
            }
            JSONObject reJson = JSONObject.parseObject(resData);
            if (reJson.get("status").toString().equals("error")) {
                map.put("code", "-4");
                map.put("info", reJson.get("validateError").toString());
                return map;
            } else {
                map.put("code", "1");
                map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
                map.put("data", "批量数据新增成功");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
